﻿using Compass.Maui.Extensions;
using Compass.Maui.Services.Cargoes;
using Compass.Wasm.Shared.Wms;

namespace Compass.Maui.ViewModels.Cargoes;

public partial class CargoesInquiryPageViewModel : BaseViewModel
{
    private readonly ICargoService _cargoService;

    public CargoesInquiryPageViewModel(ICargoService cargoService)
    {
        _cargoService = cargoService;
        GetEnumNames();
    }

    public ObservableRangeCollection<CargoDto> CargoDtos { get; } = new();

    #region 属性
    private EnumPicker warehouse;
    public EnumPicker Warehouse
    {
        get => warehouse;
        set
        {
            SetProperty(ref warehouse, value);
            SearchAll = false;
        }
    }
    public ObservableRangeCollection<EnumPicker> Warehouses { get;}=new();
    
    private EnumPicker area;
    public EnumPicker Area
    {
        get => area;
        set
        {
            SetProperty(ref area, value);
            SearchAll = false;
        }
    }

    public ObservableRangeCollection<EnumPicker> Areas { get; } = new();
    

    private EnumPicker column;
    public EnumPicker Column
    {
        get => column;
        set
        {
            SetProperty(ref column, value);
            SearchAll = false;
        }
    }
    public ObservableRangeCollection<EnumPicker> Columns { get; } = new();
    
    private EnumPicker row;
    public EnumPicker Row
    {
        get => row;
        set
        {
            SetProperty(ref row, value);
            SearchAll = false;
        }
    }

    public ObservableRangeCollection<EnumPicker> Rows { get; } = new();

    private string search;
    /// <summary>
    /// 搜索条件属性
    /// </summary>
    public string Search
    {
        get => search;
        set
        {
            search = value;
            OnPropertyChanged();
            Filter();
        }
    }
    private bool searchAll;
    /// <summary>
    /// 全范围搜索
    /// </summary>
    public bool SearchAll
    {
        get => searchAll;
        set
        {
            SetProperty(ref searchAll, value);
            Filter();
        }
    }
    private bool shortAge;
    public bool ShortAge
    {
        get => shortAge;
        set
        {
            SetProperty(ref shortAge, value);
            Filter();
        }
    }
    #endregion

    [RelayCommand]
    private async Task GetCargoDtosAsync()
    {
        await IsBusyFor(async () =>
        {
            if (IsRefreshing)
            {
                IsRefreshing = false;
                return;
            }

            try
            {
                if (SearchAll)
                {
                    CargoDtos.ReplaceRange(
                        (await _cargoService.GetMauiAllWithInventoryAsync(0, Consts.PageSize, Search))
                        .Where(x => !ShortAge || x.ShortAge));
                }
                else
                {
                    var ranks = $"{Column.Name}-{Row.Name}-";
                    if (ranks == "--") ranks = "1-1-";
                    var cargoes = await _cargoService.GetMauiAllByAreaWithInventoryAsync(
                        (Warehouse_e)Enum.Parse(typeof(Warehouse_e), Warehouse.Name),
                        (Area_e)Enum.Parse(typeof(Area_e), Area.Name), ranks, Search);
                    CargoDtos.ReplaceRange(cargoes.Where(x => !ShortAge || x.ShortAge));
                }
            }
            catch (NullReferenceException e)
            {

            }
            catch (Exception e)
            {
                await Shell.Current.DisplayAlert("Error!", $"Unable to get cargoes:{e.Message}", "OK");
            }
            finally
            {
                IsRefreshing = false;
            }
        });
    }

    [RelayCommand]
    private async Task LoadMoreAsync()
    {
        await IsBusyFor(async () =>
        {
            if (IsRefreshing)
            {
                IsRefreshing = false;
                return;
            }
            try
            {
                if (SearchAll)
                {
                    CargoDtos.AddRange((await _cargoService.GetMauiAllWithInventoryAsync(CargoDtos.Count, Consts.PageSize, Search))
                        .Where(x => !ShortAge||x.ShortAge));
                }
                else
                {
                    var ranks = $"{Column.Name}-{Row.Name}-";
                    if (ranks == "--") ranks = "1-1-";
                    var cargoes = await _cargoService.GetMauiAllByAreaWithInventoryAsync(
                        (Warehouse_e)Enum.Parse(typeof(Warehouse_e), Warehouse.Name),
                        (Area_e)Enum.Parse(typeof(Area_e), Area.Name), ranks, Search);
                    CargoDtos.ReplaceRange(cargoes.Where(x => !ShortAge||x.ShortAge));
                }
            }
            catch (NullReferenceException e)
            {

            }
            catch (Exception e)
            {
                
                await Shell.Current.DisplayAlert("Error!", $"Unable to get cargoes:{e.Message}", "OK");
            }
            finally
            {
                IsRefreshing=false;
            }
        });
    }

    private void GetEnumNames()
    {
        //初始化一些枚举值
        Warehouses.ReplaceRange(Enum.GetNames(typeof(Warehouse_e)).Select(x => new EnumPicker{ Name = x }));
        Areas.ReplaceRange(Enum.GetNames(typeof(Area_e)).Select(x => new EnumPicker { Name = x }));
        Columns.ReplaceRange(Enumerable.Range(1, 9).Select(x=>new EnumPicker{Name = x.ToString()}));
        Rows.ReplaceRange(Enumerable.Range(1, 9).Select(x => new EnumPicker { Name = x.ToString() }));

        Warehouse = Warehouses[0];
        Area = Areas[0];
        Column = Columns[0];
        Row = Rows[0];
        //Stations = Enum.GetNames(typeof(Station_e));
    }
    
    private async void Filter()
    {
        await GetCargoDtosAsync();
    }
     
}

